import React, { Component } from 'react';
import { Button, message } from 'antd';
import s from './index.module.less';
import LabelItem from '../../../components/LabelItem';
import InputModal from '../../../components/InputModal';
import MemberSelectModal from '../../../components/MemberSelectModal';
import { randomStr } from '../../../utils/util';
import isSuccess from '../../../utils/error';

export const baseClient = {
    isnew: true,
    rectype: 1,
    phone: '',
    mail: '',
    contact: '',
    title: '',
    titleid: '',
    name: '',
    members: [],
}

const baseStage = {
    "islawyerhost": true,
    "isclientlawyermanager": false,
    "ismanager": true,
    "isclientmanager": false,
    "ismember": true,
    "ishost": true,
    "islawyermanager": true,
    "iscomplete": false,
    "isclientlawyerhost": false,
    "isuserdefine": false,
    members: [],
    tasks: [],
    files: [],
    folders: [],
    info: {
        fullcourt: [],
        clerk: [],
        client: [baseClient],
        remarks: [],
        litigant: [baseClient],
    },
    name: '',
    stageid: 1,
    stageorder: 1
}

class InfoStageAdd extends Component {

    state = {}

    showAddStageModal = () => {
        this.setState({ show: true });
    }

    showAddCustomModal = () => {
        this.setState({ showInput: true });
    }

    addStage = async ({ targets }, callback) => {
        const newStages = [];
        const customStages = [];
        targets.forEach(t => {
            if (typeof t.stageid === 'string' && t.stageid.length === 16) {
                customStages.push(t);
            } else newStages.push(t);
        });
        // 筛选自定义阶段名称去服务器请求新的自定义阶段stageid
        if (customStages.length) {
            const { addCustomStage } = this.props.projectState;
            const { projecttype } = this.props.detailData;
            // 后台这个接口不支持并发请求，使用Promise.all后面的接口会报错，超级垃圾
            for (let i = 0; i < customStages.length; i++) {
                const stagename = customStages[i].stagename;
                const res = await addCustomStage({ projecttype, stagename });
                if (isSuccess(res)) {
                    const customStage = {
                        ...customStages[i],
                        ...res.data,
                    };
                    newStages.push(customStage);
                } else {
                    message.error(`${stagename}自定义阶段添加失败`);
                }
            }
        }
        const {
            detailData: { stages },
            onStagesChange
        } = this.props;

        // 默认添加的第一项为active
        const activeIndex = `${stages.length}`;

        // 设置默认值
        const newList = newStages.map(s => ({
            ...baseStage,
            ...s,
            name: s.stagename,
            // 本地添加的属性, 用于后面逻辑判断
            isNewStage: true,
        }));

        onStagesChange({ stages: [...stages, ...newList], activeIndex });
        callback && callback();
    }

    // 自定义阶段 
    addCustomStage = (stagename, callback) => {
        const { dataSource } = this.selModal.getSelState();
        if (dataSource.some(s => s.stagename === stagename)) {
            message.warn('已存在该自定义阶段名称，请不要重复添加！');
            return;
        }
        const customStage = {
            order: 0,
            datastageid: 0,
            stageid: randomStr(16), // 以这个识别自定义字段
            stagename,
            isuserdefine: true,
            selected: true,
        };
        callback && callback();
        this.selModal.setSelItems(customStage);
    }

    render() {
        const { show, showInput } = this.state;
        const { create, isBoss, detailData, projectState } = this.props;
        const { iscomplete, stages } = detailData;
        const { allStages } = projectState;

        const dataSource = allStages.filter(val => !stages.some(v => v.stageid === val.stageid));

        return (
            <div className={s.lable}>
                <LabelItem
                    col={1}
                    label={'项目阶段'}
                    optDom={(create || isBoss) && !iscomplete ? (
                        <span className="mdi mdi-plus-box" onClick={this.showAddStageModal} />
                    ) : null}
                    require={create}
                />
                <MemberSelectModal
                    isAdd
                    ref={d => this.selModal = d}
                    extraButton={<Button size="small" type="primary" onClick={this.showAddCustomModal}>自定义阶段</Button>}
                    title={'项目阶段'}
                    mainKey={'stageid'}
                    showKey={'stagename'}
                    visible={show}
                    dataSource={dataSource}
                    onOk={this.addStage}
                    onCancel={() => this.setState({ show: false })}
                />
                <InputModal
                    visible={showInput}
                    onSure={this.addCustomStage}
                    onClose={() => this.setState({ showInput: false })}
                />
            </div>
        );
    }
}

export default InfoStageAdd